package com.siyao.redvip.ui.activity;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.android.volley.http.RequestManager;
import com.android.volley.http.RequestManager.RequestListener;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.siyao.redvip.R;
import com.siyao.redvip.RedApplication;
import com.siyao.redvip.bean.TResponseBean;
import com.siyao.redvip.bean.User;
import com.siyao.redvip.bean.UserBean;
import com.siyao.redvip.callBack.CommItemClickCallBack;
import com.siyao.redvip.components.base.BaseFragmentActivity;
import com.siyao.redvip.network.NetConstans;
import com.siyao.redvip.ui.adapter.VipUserAdapter;
import com.siyao.redvip.utils.ToastUtils;
import com.siyao.redvip.utils.Track;

/**
 * 新会员管理
 * 
 * @author
 * 
 */
public class VipManageActivity extends BaseFragmentActivity {

	private LinkedList<User> mListItems;
	private EditText et_search;
	private PullToRefreshGridView mPullRefreshGridView;
	private GridView mGridView;
	private VipUserAdapter vipAdapter;
	private int currPage = 0;// 当前页
	private int total;// 总页数
	private String volunteerId;// 用户ID

	private Mode currentMode;// 上拉还是下拉状态
	private String searchName = "";

	private View namingPopView;// Popwind

	private LinearLayout tvPhone, tvClose, tvMessage;
	
	private int positionId;//当前点击的哪一个

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleText("会员管理");
		setLeftButton("返回");
	}

	@Override
	protected void beforeInit() {
		volunteerId = RedApplication.getUser().getGet_id();
		
	}

	@Override
	public void ininlazeLayout() {
		View main = getLayoutInflater().inflate(R.layout.activity_vip_manage,
				null);
		appMainView.addView(main, layoutParams);
	}

	@Override
	public void ininlazeView() {
		et_search = (EditText) findViewById(R.id.et_search);
		et_search.addTextChangedListener(new TextWatcher() {
			CharSequence temp;

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				temp = s;
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				searchName = s.toString();
				int textLength = s.length();
				vipAdapter.clear();
				if (textLength > 0) {
					// 删除按钮要显示出来
					queryDataByName(searchName);
				} else {
					currPage = 0;
					getData(1, searchName);
				}
			}
		});

		mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);
		mGridView = mPullRefreshGridView.getRefreshableView();
		mGridView.setNumColumns(3);
	


		vipAdapter = new VipUserAdapter(this);
		// 设置点击事件回调函数，弹出打电话的框框
		vipAdapter.setCommItemClickCallBack(new CommItemClickCallBack() {
			@Override
			public void click(int position) {
				if (namingPopView.getVisibility() == View.GONE) {
					namingPopView.setVisibility(View.VISIBLE);
				}
				positionId=position;
			}
		});
		mListItems = new LinkedList<User>();

		mPullRefreshGridView
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<GridView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<GridView> refreshView) {
						int flags = DateUtils.FORMAT_SHOW_TIME
								| DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL;

						String label = DateUtils.formatDateTime(
								getApplicationContext(),
								System.currentTimeMillis(), flags);
						// 更新最后刷新时间
						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);
						currentMode = refreshView.getCurrentMode();
						getData(2, searchName);// 下拉上拉刷新数据
					}
				});
		// 加载popwind
		namingPopView = findViewById(R.id.choosePop);
		tvPhone = (LinearLayout) namingPopView.findViewById(R.id.tvPhone);
		tvClose = (LinearLayout) namingPopView.findViewById(R.id.tvClose);
		tvMessage = (LinearLayout) namingPopView.findViewById(R.id.tvMessage);

		tvPhone.setOnClickListener(this);
		tvClose.setOnClickListener(this);
		tvMessage.setOnClickListener(this);

	}

	@Override
	public void ininlazeData() {
		getData(1, searchName);// 初始化数据
	}

	// 获取后台数据
	private void getData(final int flage, String name) {
		showPd();
		if (currPage == 0) {
			currPage = 1;
		} else {
			currPage++;
		}

		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("get_id", volunteerId + "");
		parmas.put("currPage", currPage + "");
		parmas.put("name", name);
		RequestManager.getInstance(this).post(NetConstans.USER_LIST, parmas,
				new RequestListener() {
					@Override
					public void onSuccess(String response, String url,
							int actionId) {
						Track.i(response);
						TResponseBean<User> data = gson.fromJson(response,
								new TypeToken<TResponseBean<User>>() {
								}.getType());
						int stat = data.getStatus();
						if (stat == 1) {
							total = Integer.parseInt(data.getTotal());
							currPage = Integer.parseInt(data.getCurrPage());
							if (currPage <= total) {
								List<User> list = data.getData();
								for (User userBean : list) {
									if (flage == 1) {
										mListItems.addLast(userBean);
										vipAdapter.setUsers(mListItems);
										mGridView.setAdapter(vipAdapter);
									} else if (flage == 2) {
										mListItems.addLast(userBean);
										vipAdapter.setDataChanged(mListItems);
									}
								}
							} else {
								ToastUtils.makeMesageShort(
										VipManageActivity.this, "没有数据!");
							}
						} else {
							ToastUtils.makeMesageShort(VipManageActivity.this,
									getString(R.string.server_error));
						}
						// 当数据加载完成，需要调用onRefreshComplete.
						mPullRefreshGridView.onRefreshComplete();
						dismissPd();
					}

					@Override
					public void onRequest() {

					}

					@Override
					public void onError(String errorMsg, String url,
							int actionId) {
						dismissPd();
						ToastUtils.makeMesageShort(VipManageActivity.this,
								getString(R.string.server_error));
						// 当数据加载完成，需要调用onRefreshComplete.
						mPullRefreshGridView.onRefreshComplete();
					}
				}, 1);
	}

	/**
	 * 根据名字搜索数据
	 * 
	 * @param name
	 */
	private void queryDataByName(String name) {
		showPd();
		if (!TextUtils.isEmpty(name)) {
			currPage = 1;
		}

		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("volunteerId", volunteerId + "");
		parmas.put("currPage", currPage + "");
		parmas.put("name", name);
		RequestManager.getInstance(this).post(NetConstans.USER_LIST, parmas,
				new RequestListener() {
					@Override
					public void onSuccess(String response, String url,
							int actionId) {
						TResponseBean<User> data = gson.fromJson(response,
								new TypeToken<TResponseBean<User>>() {
								}.getType());
						int stat = data.getStatus();
						if (stat == 1) {
							total = Integer.parseInt(data.getTotal());
							currPage = Integer.parseInt(data.getCurrPage());
							if (currPage <= total) {
								List<User> list = data.getData();
								for (User userBean : list) {
									mListItems.addLast(userBean);
									vipAdapter.setDataChanged(mListItems);
								}
							} else {
								ToastUtils.makeMesageShort(
										VipManageActivity.this, "没有数据!");
							}
						} else {
							ToastUtils.makeMesageShort(VipManageActivity.this,
									getString(R.string.server_error));
						}
						// 当数据加载完成，需要调用onRefreshComplete.
						mPullRefreshGridView.onRefreshComplete();
						dismissPd();
					}

					@Override
					public void onRequest() {

					}

					@Override
					public void onError(String errorMsg, String url,
							int actionId) {
						dismissPd();
						ToastUtils.makeMesageShort(VipManageActivity.this,
								getString(R.string.server_error));
						// 当数据加载完成，需要调用onRefreshComplete.
						mPullRefreshGridView.onRefreshComplete();
					}
				}, 1);
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		Intent intent;
		String tel=mListItems.get(positionId).getGet_tele();
		int key = v.getId();
		switch (key) {
		case R.id.tvPhone:
			if(tel!=null){
				intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+ tel));
				startActivity(intent);
			}else{
				ToastUtils.makeMesageShort(this, "该会员没有填写手机号码！");
			}
			namingPopView.setVisibility(View.GONE);
			break;
		case R.id.tvClose:
			if (namingPopView.getVisibility() == View.VISIBLE) {
				namingPopView.setVisibility(View.GONE);
			}
			break;
		case R.id.tvMessage:
			if(tel!=null){
				Uri smsToUri = Uri.parse("smsto:"+tel);
				intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
				intent.putExtra("sms_body", "");
				startActivity(intent);
			}else{
				ToastUtils.makeMesageShort(this, "该会员没有填写手机号码！");
			}
			namingPopView.setVisibility(View.GONE);
			break;

		case R.id.choosePop:
			if (namingPopView.getVisibility() == View.VISIBLE) {
				namingPopView.setVisibility(View.GONE);
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onBackPressed() {
		if (namingPopView.getVisibility() == View.VISIBLE) {
			namingPopView.setVisibility(View.GONE);
		}
	}
}
